const util = require('../../utils/util.js')
let p

Page({

    data: {
		staticDomain: util.config('staticDomain'),
		lostId: '',
		lostType: '',
		lostTitle: '',
		lostDate: 0,
		lostContent: '',
		lostAddress: '',
		lostContact: '',
		lostPhotoCount: 0,
		detailLoaded: false,
		loadingPanel: {
			tip: '加载中'
		}
    },

    onLoad: function(params) {
		p = this
		if (!params.lostId) {
			util.error('参数错误', '似乎出现了一些意外的问题，即将返回上一层哦', wx.navigateBack)
			return
		}
		util.userLogin({
			p,
			scene: 'other',
			complete: () => {
				util.showNotices(p)
				p.loadLostData({
					lostId: params.lostId
				})
			},
			fail: (title, msg) => {
				wx.navigateBack({
					delta: 1
				})
				util.error(title, msg)
			},
			notBind: () => {
				util.modal('绑定提示', '只有登录和绑定身份后才能使用此功能哦，即将跳转到主页', () => {
					wx.switchTab({
						url: '/pages/home/home'
					})
				})
			}
		})
    },

    onUnload: () => {
		util.unloadPage('lostDetail')
    },

	loadLostData: (obj) => {
		const { lostId, sync, success, fail } = obj || {}
		util.request({
			source: 'lostDetail',
			method: sync ? 'put' : 'get',
			uri: `user/lost/${lostId}`,
			success: (lostData) => {
				const { lostType, lostTitle, lostDate, lostContent, lostAddress, lostContact, lostPhotoCount } = lostData
				p.setData({
					lostId,
					lostType,
					lostTitle,
					lostDate,
					lostContent,
					lostAddress: lostType == 2 ? '实训楼6-403 失物招领中心' : lostAddress,
					lostContact: lostType == 2 ? '15625571656' : lostContact,
					lostPhotoCount,
					detailLoaded: true
				})
				wx.stopPullDownRefresh()
				util.hideLoadingPanel(p)
				if(success)
					success(lostData)
			},
			fail: (code, msg) => {
				wx.stopPullDownRefresh()
				util.hideLoadingPanel(p)
				if(code == '-2100') {
					util.error('信息未过审', '此失物招领信息还未过审，暂时无法查看，如果您是发布者请耐心等待审核哦，或者联系微信加急：aidoukj，即将返回上一层', wx.navigateBack)
					return
				}
				if (code == '-2101') {
					util.error('信息已过期', '此失物招领信息已经过期，无法继续查看，即将返回上一层', wx.navigateBack)
					return
				}
				util.error('加载失败', util.errorHandler(code, msg), () => wx.switchTab({
					url: '/pages/home/home'
				}))
				if(fail)
					fail(code, msg)
			}
		})
	},

	copyContent: () => {
		wx.setClipboardData({
			data: p.data.lostContent
		})
	},

	copyAddress: () => {
		wx.setClipboardData({
			data: p.data.lostAddress.toString()
		})
	},

	copyContact: () => {
		wx.setClipboardData({
			data: p.data.lostContact.toString()
		})
	},

	previewPhoto: (e) => {
		const url = e.currentTarget.dataset.url
		if (!url)
			return
		wx.previewImage({
			urls: [url],
		})
	},

    onPullDownRefresh: function() {
		util.showLoadingPanel(p, '加载中')
		p.loadLostData({
			lostId: p.data.lostId,
			sync: true
		})
    },

    onShareAppMessage: function() {
		return {
			title: `${['寻物', '招领', '招领'][p.data.lostType]}启事：${p.data.lostTitle}`,
			path: `/pages/lostDetail/lostDetail?lostId=${p.data.lostId}`
		}
    }

})